package com.bee.auth.controller;

import com.bee.commons.vo.Result;
import com.bee.auth.client.util.HttpSecurityUtil;
import com.bee.auth.common.vo.UserVO;
import com.bee.auth.service.LoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Damin.yang
 * @date 2019/08/16 11:16
 */
@Slf4j
@Api(tags = "登录")
@Controller
public class LoginController {

    @Autowired
    private LoginService loginService;

    @ApiOperation(value = "登录接口", notes = "用户登录")
    @PostMapping("login")
    @ResponseBody
    public Result<UserVO> login(
            @ApiParam("账号") @RequestParam String username,
            @ApiParam("密码") @RequestParam String password
    ) {
        try {
            UserVO userVO = loginService.login(username, password);
            return Result.success(userVO);
        } catch (Exception e) {
            log.error(">>> login error:", e);
            return Result.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "登录接口", notes = "用户登录-设置cookie")
    @PostMapping("loginCookie")
    public String login(
            @ApiParam("账号") @RequestParam String username,
            @ApiParam("密码") @RequestParam String password,
            HttpServletResponse response
    ) {
        try {
            UserVO userVO = loginService.login(username, password);
            Cookie cookie = new Cookie(HttpSecurityUtil.TOKEN_NAME, userVO.getToken());
            cookie.setHttpOnly(true);
            cookie.setPath("/");
            cookie.setDomain("bee.com");
            cookie.setMaxAge(3600 * 100);
            response.addCookie(cookie);
            return null;
        } catch (Exception e) {
            log.error(">>> login error:", e);
            return null;
        }
    }
}
